package oneweone.com.ssldemo;

import android.Manifest;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.InputStream;

import oneweone.com.ssldemo.http.Api;
import oneweone.com.ssldemo.http.AuthenticationParameters;
import oneweone.com.ssldemo.util.IOUtil;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Api mApi = null;
    private String mClientCertificatePassword = "jiaziying9966!";
    private String mClientCertificateName = "client.p12";
    private String mCaCertificateName = "httpca.so";

        private String URL = "http://api.gaga.76iw.com/v1/task/list-tasklist";
//    private String URL = "https://www.google.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initHttp();
        checkSdCardPermission();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_btn:
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            Log.e("https", "result:" + mApi.doGet(URL));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();

                break;
        }
    }

    private void initHttp() {
        try {
            AuthenticationParameters authParams = new AuthenticationParameters();
            authParams.setClientCertificate(getClientCertFile());
            authParams.setClientCertificatePassword(mClientCertificatePassword);
            authParams.setCaCertificate(readCaCert());

            mApi = new Api(authParams);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private File getClientCertFile() {
        File externalStorageDir = Environment.getExternalStorageDirectory();
        return new File(externalStorageDir, mClientCertificateName);
    }

    private String readCaCert() throws Exception {
        AssetManager assetManager = getAssets();
        InputStream inputStream = assetManager.open(mCaCertificateName);
        return IOUtil.readFully(inputStream);
    }

    public void checkSdCardPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }
}
